package com.tmc.platform.jinri.util;

import java.util.HashMap;
import java.util.Map;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.junit.Test;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.tmc.bean.common.AccountBean;
import com.tmc.bean.common.CommonResult;
import com.tmc.util.HttpClientUtil;

public class OpenJinriUtil {
	
	public static String userName = "shenzhentehang";
	public static String password = "123456";
	
	//http://www.air9.cn/Admin/Submit?UserName=&Password=
	public static String login_url = "http://www.air9.cn/Admin/Submit";
	//http://www.air9.cn/PriceParity/QueryOtherPolicyParity?orderid=17103056993436&Third=15 匹配其他政策
	public static String other_policy_url = "http://www.air9.cn/PriceParity/QueryOtherPolicyParity";
	//http://www.air9.cn/OrderNewList/OrderSearchList?pnr=
	public static String order_url = "http://www.air9.cn/OrderNewList/OrderSearchList";
	//http://www.air9.cn/OrderCreate/EtermRtPnr?pnrInfo=&consumerClass=1&customer=&Office_Id= 
	public static String create_order_url ="http://www.air9.cn/OrderCreate/EtermRtPnr";
	
	public static Map<String, CloseableHttpClient> clients = new HashMap<String, CloseableHttpClient>();
	public static AccountBean account = null;

	public static CloseableHttpClient getClient(String random){
		if(account == null){
			account = new AccountBean(userName, password, new BasicCookieStore());
		}
		if(clients.get(random) == null){
			clients.put(random, HttpClients.custom().setDefaultCookieStore(account.getCookie()).build());
		}
		return clients.get(random);
	}
	
	/**
	 * 登陆air9
	 * 
	 * @param random
	 * @return CommonResult
	 */
	public static CommonResult login(String random){
		CloseableHttpClient client = getClient(random);
		Map<String,String> map =getLoginParams();
		String jsonString = HttpClientUtil.sendHttpPost(client, login_url, map);
		JSONObject jsonObject = JSON.parseObject(jsonString);
		if(jsonObject.getString("Msg").equals("登陆成功")){//indexOf("登陆成功")>-1
			System.out.println("登陆成功");
			return CommonResult.makeSuccess(jsonString);
		}
		return CommonResult.makeFail("未知错误！");
	}
	
	private static Map<String,String> getLoginParams(){
		Map<String,String> map = new HashMap<>();
		map.put("UserName", account.getUserName());
		map.put("Password", account.getPassword());
		return map;
	}
	
	/**
	 * 查询政策
	 * Third 13:运价直连(今通),10:517(517NA),11:8000YI(8000YI),12:TraFree(TraFree),14:MEIYA(美亚),15:TRAVELZEN(真旅),16:TWFLIGHT(东立)
	 * @param random
	 * @param orderid
	 * @param Third
	 * @return jsonString
	 */
	public static String getOtherPolicy(String random, String orderid, String third){
		CommonResult cr = login(random);
		if(!cr.isSuccess()){
			return null;
		}
		CloseableHttpClient client = getClient(random);
		String httpUrl = getOtherPolicyUrl(orderid,third);
		String jsonString = HttpClientUtil.sendHttpGet(client, httpUrl);
		try {
			client.close();
			if (clients.size() == 1) {
				clients = new HashMap<String, CloseableHttpClient>();
			} else {
				clients.remove(random);
			}
		} catch (Exception e) {
		}
		return jsonString;
	}
	
	private static String getOtherPolicyUrl(String orderid, String third) {
		return other_policy_url+"?orderid="+orderid+"&Third="+third;
	}
	
	/**
	 * 创建订单并返回订单编号
	 * 
	 * @param random
	 * @param pnr
	 * @return orderid
	 */
	public static CommonResult getCreateOrder(String random,String pnr){
		CommonResult cr = login(random);
		if(!cr.isSuccess()){
			return null;
		}
		CloseableHttpClient client = getClient(random);
		Map<String,String> map = getCreateOrderParams(pnr);
		String jsonString = HttpClientUtil.sendHttpPost(client, create_order_url, map);
		try {
			client.close();
			if (clients.size() == 1) {
				clients = new HashMap<String, CloseableHttpClient>();
			} else {
				clients.remove(random);
			}
		} catch (Exception e) {
			return CommonResult.makeFail("系统错误");
		}
		if(jsonString == null){
			return CommonResult.makeFail("系统错误");
		}
		JSONObject jsonObject = null;
		try{
			jsonObject = JSON.parseObject(jsonString);
		}catch (Exception e){
			return CommonResult.makeFail("系统错误");
		}
		//JSONObject jsonObject = JSON.parseObject(jsonString);
		if (jsonObject.getString("Success").equals("true")) {
			return CommonResult.makeSuccess("创建订单成功", jsonObject.getString("order_id"));
		} else if (jsonObject.getString("Success").equals("false")
				&& jsonObject.getString("Message").equals("SAME_PNR")) {
			return CommonResult.makeSuccess("订单已存在，且不为取消订单", jsonObject.getString("order_id"));
		} else if (jsonObject.getString("Success").equals("false")
				&& (jsonObject.getString("Message").equals("EMPTY_PNR")
						|| jsonObject.getString("Message").equals("INVALID_PARAM"))) {
			return CommonResult.makeFail("无效的pnr");
		}
		return CommonResult.makeFail("系统错误");
	}
	
	private static Map<String, String> getCreateOrderParams(String pnr){
		// var data = {
		// pnrInfo: pnrInfo,
		// consumerClass: consumerClass,
		// MerchantId: MerchantId, //consumerClass=0
		// customer: perinfo,  //consumerClass=1
		// Office_Id: office
		// };
		Map<String, String> map = new HashMap<>();
		map.put("pnrInfo", pnr);
		map.put("consumerClass", "1");// 0为MerchantId 或 1为customer
		map.put("customer", "");
		map.put("Office_Id", "SZX453");
		return map;
	}
	
	/**
	 * 通过pnr查询订单
	 * 
	 * @param random
	 * @param pnr
	 * @return orderid
	 */
	public static String getOrder(String random,String pnr){
		CommonResult cr = login(random);
		if(!cr.isSuccess()){
			return null;
		}
		CloseableHttpClient client = getClient(random);
		String httpUrl = getOrderUrl(pnr);
		String html = HttpClientUtil.sendHttpGet(client, httpUrl);
		try {
			client.close();
			if (clients.size() == 1) {
				clients = new HashMap<String, CloseableHttpClient>();
			} else {
				clients.remove(random);
			}
		} catch (Exception e) {
		}
		return getOrderResult(html);
	}
	
	private static String getOrderUrl(String pnr){
		return "http://www.air9.cn/OrderNewList/OrderSearchList?pnrcode="+pnr;
	}
	
	private static String getOrderResult(String html){
		Document doc = Jsoup.parse(html);
		Element element = doc.select("#txtSearch").get(0);
		String JsonString = element.attr("value");
		JSONObject object = JSON.parseObject(JsonString);
		JSONArray array = object.getJSONArray("rows");
		String orderId= null;
		if(!(array == null || array.isEmpty())){
			JSONObject obj = array.getJSONObject(0);
			orderId=obj.getString("order_id");
		}
		return orderId;
	}
	
	@Test
	public void createOrder(){
		CommonResult cr = getCreateOrder(Math.random()+"","");
		System.out.println(cr.getObj());
	}
	
	@Test
	public void getOtherPolicyTest(){
		String html = getOtherPolicy(Math.random()+"","null","10");
		System.out.println(html);
	}
	
	@Test
	public void getOrderTest(){
		String orderId = getOrder(Math.random()+"","ASD456");//KNDR5R
		System.out.println(orderId);
	}
}
